import pageination from '../../components/pageination/pageination.vue'

/**
 * 文件信息对象
 */
function FileInfo() {
  this.name = ''; //文件名
  this.url = ''; //
  this.suffix = ''; //后缀
  this.size = "0"; //大小
}

export default {
	data() {
		return {
			//数据
      total: 0, //总条数
      page: 1, //当前页
      size: 10,//每页显示条数
      search: '',
      validate: {}, //验证对象
			ApplicationStatus: false,
			Application: false,
			curId: 0,
			uploadNum: 0,
      tempName: '',
      material: {}, //资料库对象
      materialList: [], //资料库集合
      textMaterialList: [], //文本资料集合
      imgMaterialList: [], //图片集合
      vdioMaterialList: [], //视频集合
		}
	},
	components: {
		pageination
	},
	created() { //调用方法
	},
	mounted() {
    let that = this;
	  //校验名称重复
    $.validator.addMethod("checkNameRepeat", function(value, element, params) {
      let flg = false;
      if(that.material.id != null && (value == that.tempName)) {
        flg = true;
      } else {
        $.ajax({
          type: "POST",
          async: false,
          url: that.urls.checkMaterialName,
          data: JSON.stringify({
            "name": value
          }),
          dataType: "json",
          contentType: "application/json",
          success: function(data) {
            if(data.success) {
              flg = !data.data;
            }
          }
        });
      }
      return this.optional(element) || flg;
    }, "该标题已存在！");

    //加载表单验证
    that.validate = $("#materialForm").validate({
      ignore: [],
      rules: {
        name: { // 政策发布名称
          required: true,
          maxlength: 50,
          checkNameRepeat: true
        },
        type: { // 类型
          required: true,
          checkTypeRepeat: true
        },
        url: { // 文件地址
          required: true,
          maxlength: 500
        }
      },
      messages: {
        name: { // 政策发布名称
          required: "请输入标题！",
          maxlength: "标题最多只能输入50个字！"
        },
        type: { // 类型
          required: "请选择类型！"
        },
        url: { // 文件地址
          required: "请选择文件！",
          maxlength: "文件地址超长！"
        }
      },
//			errorElement: "em",
//			errorPlacement: function(error, element) {
//				error.appendTo(element.parents(".error-box").children(".error-msg"));
//			}
    });
  },
	methods: { //写函数方法
		//页码切换执行方法
		pageFn: function(val, pid) {
			this.page = parseInt(val);
			//此处调列表数据接口
      this.searchTodo();
		},
		/**返回子组件用户选择的一页显示条数**/
		obtainChild: function(data) {
			this.row = data;
		},
		//人工录入及修改模态框
		manually:function(material){
      //清空源数据
		  $("input[type=reset]").trigger("click");
      this.validate.resetForm();
      this.material = {};
      this.textMaterialList = [];
      this.imgMaterialList = [];
      this.vdioMaterialList = [];

      //重新渲染数据
      if (material != null) {
        this.tempName = material.name;
        this.material = material;
        this.textMaterialList = material.textMaterial == null || material.textMaterial == '' ? [] : JSON.parse(material.textMaterial);
        this.imgMaterialList = material.imgMaterial == null || material.imgMaterial == '' ? [] : JSON.parse(material.imgMaterial);
        this.vdioMaterialList = material.vdioMaterial == null || material.vdioMaterial == '' ? [] : JSON.parse(material.vdioMaterial);
      }

      //显示弹框
		  this.ApplicationStatus = true;
		},
		//查看
		toView:function(material){
      //数据渲染数据
		  this.material = material;
      this.textMaterialList = material.textMaterial == null || material.textMaterial == '' ? [] : JSON.parse(material.textMaterial);
      this.imgMaterialList = material.imgMaterial == null || material.imgMaterial == '' ? [] : JSON.parse(material.imgMaterial);
      this.vdioMaterialList = material.vdioMaterial == null || material.vdioMaterial == '' ? [] : JSON.parse(material.vdioMaterial);

      //显示弹框
		  this.Application = true;
		},
		//关闭模态框
		closeModel: function() {
			this.Application = false;
			this.ApplicationStatus = false;
		},
		touchOffIdInput(n) {
			this.uploadNum = n;
			if(n == 1) {
				$("#handIdFront").click();
			}
		},
    //预览
    preview: function(url,msg) {
      if (url == null || url == "") {
        if (msg == null || msg == "") {
          msg = "附件";
        }
        layer.msg("暂无" + msg + "！");
      } else {
        window.open(this.urls.baseUrl + url);
      }
    },

    /**
     * 删除资料
     * @param type 文件类型（0：文本；1：图片；2：视频）
     * @param index 文件列表所在下标
     */
    deleteMaterial: function(type, index) {
		  if (type == null || index == null) {
		    return;
      }
      switch (type) {
        case 0 :
          this.textMaterialList.splice(index);
          break;
        case 1 :
          this.imgMaterialList.splice(index);
          break;
        case 2 :
          this.vdioMaterialList.splice(index);
          break;
      }
    },
    /**
     上传文件（为了避免数据冲突问题，这里选择了同步上传）
     type:0 //文本
     type:1 //图片
     type:2 //视频
     */
		idFrontImg: function(type) {
		  var that = this;
		  var type = type;
		  if (type == null) {
		    console.log("上传文件异常：输入type类型为空");
		    return;
      }
      var file = event.currentTarget.files[0];
      if (!that.fileGlobalFilter(file)) {
        return;
      }
      let formData = new FormData();
      formData.append('fileNames', file);
      $.ajax({
        type: "POST",
        async: false,
        url: that.urls.upload,
        data: formData,
        processData: false,  // 告诉jQuery不要去处理发送的数据
        contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
        dataType: "json",
        success: function(res){
          if(res.success) {
            let fileInfo = res.data[0];
            let fi = new FileInfo();
            fi.name = fileInfo.name;
            fi.size = that.renderSize(file.size);
            fi.suffix = that.getFileSuffix(fileInfo.name);
            fi.url = fileInfo.url;
            switch (type) {
              case 0 :
                that.textMaterialList.push(fi);
                break;
              case 1 :
                that.imgMaterialList.push(fi);
                break;
              case 2 :
                that.vdioMaterialList.push(fi);
                break;
            }
          }
        }
      });
		},
    //搜索数据列表
    searchTodo: function() {
      let that = this;
      that.$post(
        that.urls.getMaterialPageInfo, {
          "pageNum": that.page,
          "pageSize": that.size,
          "search": that.search
        }
      )
      .then(function(res) {
        if(res.success) {
          that.materialList = res.pageInfo.list;
          that.total = res.pageInfo.total;
          that.page = res.pageInfo.pageNum;
        }
      })
    },
    //保存
    saveData: function() {
      let that = this;
      let flg = that.validate.form();
      if(flg) {
        let dataObj = combinationFormObject(that.validate.currentForm);
        dataObj["textMaterial"] = JSON.stringify(that.textMaterialList);
        dataObj["imgMaterial"] = JSON.stringify(that.imgMaterialList);
        dataObj["vdioMaterial"] = JSON.stringify(that.vdioMaterialList);
        that.$post(
          that.urls.addMaterial,
          dataObj
        )
        .then(function(res) {
          let msg = "";
          if(res.success) {
            msg = "保存成功！";
            that.searchTodo();
            that.ApplicationStatus = false;
          } else {
            msg = "保存失败！";
          }
          layer.msg(msg, {
            time: 3000, //3s后自动关闭
          });
        })
      }
    },
    //修改
    updateData: function() {
      let that = this;
      let flg = that.validate.form();
      if(flg) {
        let dataObj = combinationFormObject(that.validate.currentForm);
        dataObj["textMaterial"] = JSON.stringify(that.textMaterialList);
        dataObj["imgMaterial"] = JSON.stringify(that.imgMaterialList);
        dataObj["vdioMaterial"] = JSON.stringify(that.vdioMaterialList);
        that.$post(
          that.urls.updateMaterial,
          dataObj
        )
        .then(function(res) {
          let msg = "";
          if(res.success) {
            msg = "修改成功！";
            that.searchTodo();
            that.ApplicationStatus = false;
          } else {
            msg = "修改失败！";
          }
          layer.msg(msg, {
            time: 3000, //3s后自动关闭
          });
        })
      }
    },
    //删除
    deleteData: function(id) {
      let that = this;
      layer.confirm('你确定要删除吗?', {icon: 3, title:'提示'}, function(index){
        if(id != null) {
          //初始化下载发布分页信息
          that.$post(
            that.urls.deleteMaterial, {
              "id": id
            }
          )
          .then(function(res) {
            let msg = "";
            if(res.success) {
              msg = '删除成功！';
              //重新渲染数据
              that.searchTodo();
            } else {
              msg = '删除失败！';
            }
            layer.msg(msg, {
              time: 3000, //3s后自动关闭
            });
          })
        }
      });
    },
    //资料下载
    download: function (url) {
      if (url == null || url == "") {
        layer.msg("暂无资料", {
          time: 3000, //3s后自动关闭
        });
        return;
      }
      window.location.href = this.urls.download + "?path=" + url;
    },
    //资料打包下载
    downloadPack: function (materialData) {
      if (materialData == null || materialData == "") {
        layer.msg("暂无资料", {
          time: 3000, //3s后自动关闭
        });
        return;
      }
      let materialList = JSON.parse(materialData);
      let urls = "";
      for (let i = 0,len = materialList.length; i < len;i++) {
        urls += materialList[i].url + ";";
      }
      if (urls == null || urls == "") {
        layer.msg("暂无资料", {
          time: 3000, //3s后自动关闭
        });
        return;
      }
      //清除最后一个分号
      urls = urls.substring(0, urls.length - 1);
      window.location.href = this.urls.downloadPack + "?paths=" + urls;
    },
	}
}
